package com.pandacc.common.utils;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;

/**
 * 提供取{@link DataSource}, {@link JdbcTemplate}的辅助类
 * @author Administrator
 *
 */
public class ServiceDaoUtils extends DataSourceUtils{
	private static Logger logger = Logger.getLogger(ServiceDaoUtils.class);

	public static DataSource getDataSource(ApplicationContext context, String beanId) throws Exception{
		return getDataSource(context,beanId,null);
	}
	
	public static DataSource getDataSource(ApplicationContext context, String beanId, Class<? extends DataSource> className) throws Exception{
		if (context == null) {
			logger.error("The input ApplicationContext object is null.");
			throw new Exception("Cannot get datasource due to input ApplicationContext object is null.");
		}
		DataSource ds = null;
		if (className==null) {
			try{
				ds = (DataSource) context.getBean(beanId);
				return ds;
			}catch(ClassCastException e){
				logger.error(String.format("Failed to get DataSource with the bean id: %s.", beanId));
				throw e;
			}
		}
		ds = context.getBean(beanId, className);
		return ds;
	}
	
	public static JdbcTemplate getJdbcTemplate(DataSource dataSource){
		if (dataSource == null) {
			logger.error("The input dataSource object is null.");
			return null;
		}
		return new JdbcTemplate(dataSource);
	}
	
	public static JdbcTemplate getJdbcTemplate(ApplicationContext context, String beanId) throws Exception{
		return getJdbcTemplate(context, beanId, null);
	}
	
	public static JdbcTemplate getJdbcTemplate(ApplicationContext context, String beanId, Class<? extends DataSource> className) throws Exception{
		DataSource ds = getDataSource(context, beanId, className);
		JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
		return jdbcTemplate;
	}
	
}
